# 2 两数相加
# leetcode第2题: https://leetcode.cn/problems/add-two-numbers/
# Date: 2024/10/15

from typing import Optional


class ListNode:
    """定义一个链表
    """

    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

    def __str__(self):
        pstr = '['
        current = self
        while current:
            pstr += str(current.val) + ', '
            current = current.next
        return pstr.rstrip(', ') + "]"


def addTwoNumbers(l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
    result = ListNode()
    current = result
    add = 0
    while True:
        val1 = 0 if not l1 else l1.val
        val2 = 0 if not l2 else l2.val
        current.val = (val1 + val2 + add) % 10
        add = 1 if val1 + val2 + add >= 10 else 0
        if not l1.next and not l2.next:
            if add:
                current.next = ListNode(1)
            return result
        l1 = l1.next if l1.next else ListNode(0)
        l2 = l2.next if l2.next else ListNode(0)
        current.next = ListNode()
        current = current.next


if __name__ == '__main__':
    l1 = ListNode(2, ListNode(4, ListNode(3)))
    l2 = ListNode(5, ListNode(6, ListNode(4, ListNode(1))))
    print(addTwoNumbers(l1, l2))
    l1 = ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9)))))))
    l2 = ListNode(9, ListNode(9, ListNode(9, ListNode(9))))
    print(addTwoNumbers(l1, l2))
